package tr.edu.yildiz.ce.dap.appagent.process;

import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.AbstractCommand;
import tr.edu.yildiz.ce.dap.appagent.command.deployment.base.CommandFactory;
import tr.edu.yildiz.ce.dap.appagent.exception.BasicAgentException;
import tr.edu.yildiz.ce.dap.appagent.manager.AgentProcessManager;
import tr.edu.yildiz.ce.dap.appagent.model.DapMessage;
import tr.edu.yildiz.ce.dap.appagent.process.base.AbstractProcess;
import tr.edu.yildiz.ce.dap.appagent.service.MessageConverter;
import tr.edu.yildiz.ce.dap.appagent.util.AgentProperties;

public class DeploymentProcess extends AbstractProcess implements Runnable{
	
	String commandXml;
	AbstractCommand command;
	SelectionKey skey;
	
	Charset charset = Charset.forName(AgentProperties.getInstance().getENCODING());
    CharsetEncoder encoder = charset.newEncoder();
	
	public DeploymentProcess(AgentProcessManager processManager,SelectionKey skey,String commandXml) {
		super(processManager);
		this.commandXml = commandXml;
		this.skey = skey;
	}
	
	private void reply(DapMessage msg){
		SocketChannel client = (SocketChannel) skey.channel();
		try{
			client.write(encoder.encode(CharBuffer
					.wrap(MessageConverter.convertToXML(msg))));
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			skey.cancel();
			try{
				client.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void run() {
		DapMessage msg = null;
		try {
			msg = MessageConverter.convertToObject(commandXml);
		} catch (Exception e) {
			e.printStackTrace();
		}
		AbstractCommand command = CommandFactory.createCommand(msg, this);
		try {
			DapMessage response = command.execute(msg);
			reply(response);
		} catch (BasicAgentException e) {
			e.printStackTrace();
			try {
				command.rollback(msg);
			} catch (BasicAgentException e1) {
				e1.printStackTrace();
			}
		}
	}
	

}
